package cn.yunyichina.provider.bone.listener;

import cn.yunyichina.provider.bone.dao.AdmissionsDao;
import cn.yunyichina.provider.bone.entity.Admissions;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.XmlUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.listener.MessageListener;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhuxp on 2018/2/8.
 *
 * @param
 * @Descrition
 */
public class BoneAdmissionsWechatPayMessageListener implements MessageListener<Integer, String> {
    private Logger logger = LoggerFactory.getLogger(BoneAdmissionsWechatPayMessageListener.class);

    @Autowired
    private AdmissionsDao admissionsDao;

    @Override
    public void onMessage(ConsumerRecord<Integer, String> integerStringConsumerRecord) {
        String xmlString = integerStringConsumerRecord.value();
        logger.info("BoneAdmissionsWechatPayMessageListener.onMessage.xmlString -> {}", xmlString);
        try {
            Map<String, String> doc = XmlUtils.xmlToMap(xmlString);
            String orderNo = doc.get("out_trade_no");
            String appId = doc.get("appid");
            String transactionId = doc.get("transaction_id");
            String attach = doc.get("attach");
            JSONObject jsonObj = JSONObject.parseObject(attach);
            String payMode = jsonObj.getString("pay_mode");
//            Float payAmount = Float.parseFloat((String) doc.get("total_fee"));
            BigDecimal payAmount = new BigDecimal( doc.get("total_fee")).multiply(new BigDecimal(100));

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("order_no", orderNo);
            Response ordResponse = BaseService.callUnderlineFromInternal("", "yyt.base.order.by.order.no.out.get",
                    JsonUtils.toJsonString(dataMap));
            if("0".equals(ordResponse.getResultCode())) {
                OrderExtVo vo = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
                vo.setPayTime(DateUtils.dateToString(new Date()));
                vo.setOrderStatusWaitWrite();//2 待审核状态
                vo.setUpdateTime(DateUtils.dateToString(new Date()));
                vo.setPayStatusPayed();
                vo.setPayAppId(appId);
                vo.setPayMode(Short.parseShort(payMode));
                // 支付流水
                vo.setPaymentDealId(transactionId);
                logger.info("BoneWechatPayMessageListener, updateOrderExtVo=" + JSONObject.toJSONString(vo));
                Response response = BaseService.callUnderlineFromInternal("",
                        "yyt.base.order.update", JsonUtils.toJsonString(vo));
                logger.info("BoneWechatPayMessageListener onMessage 更新订单 response:{}", JSON.toJSONString(response));

                //更新报名记录
                Admissions admissions =admissionsDao.queryAmissionsByOrderNo(orderNo);
                admissions.setPayStatus((short) 3);
                admissions.setOrderStatus((short) 2);
                admissions.setPaymentDealId(transactionId);
                admissions.setPayTime(DateUtils.getDateTimeStr());
                admissions.setUpdateTime(DateUtils.getDateTimeStr());
                admissionsDao.update(admissions);

                //推送短信
                Map<String, Object> data = new HashMap<>();
                data.put("to_user", vo.getUserMobile());
                data.put("msg_type", 99);
                Map<String, String> msgContent = new HashMap<>();
                msgContent.put("user_name", vo.getUserName());
                data.put("msg_content", msgContent);
                String dataJson = JSON.toJSONString(data);
                // 发送短信给患者
                logger.info("发送短信，参数: " + dataJson);
                MessageService.callUnderlineFromInternal("yyt.message.msg.sms.send", dataJson);
            }else{
                logger.info("BoneWechatPayMessageListener 查不到该订单" + orderNo);
            }
        }catch (Exception e){
            logger.error("onMessage error.", e);
        }
        logger.info("onMessage end.");
    }
}
